/* Copyright © 2023 - 2024 Coremail论客
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


import hilog from "@ohos.hilog";

export type LogHandler = (level: hilog.LogLevel, t: Date, log: string) => void;

//外界传入一个回调,当每次进行日志操作时,可以执行一次这个回调.
let _handler: LogHandler;


const _taskLogMap: Map<string, Logger> = new Map();

export function getTaskLogger(name: string): Logger {
  if (_taskLogMap.has(name)) {
    return _taskLogMap.get(name);
  } else {
    let logger = getLogger(`[${name}]`);
    _taskLogMap.set(name, logger);
    return logger;
  }
}


function toString(args: unknown[], maxLength?: number): string {
  let s = args.map(v => {
    if (typeof v == "string") {
      return v;
    } else if (v && v['toLogString']) {
      return v['toLogString']();
    } else {
      try {
        const s = JSON.stringify(v);
        return s;
      } catch (e: unknown) {
        return v as string;
      }
    }
  }).join(" ");
  if (maxLength && maxLength > 0 && s.length > maxLength) {
    s = s.substring(0, maxLength);
  }
  return s;
}

let _logLevel: hilog.LogLevel = hilog.LogLevel.DEBUG;

export function setLogLevel(level: hilog.LogLevel): void {
  _logLevel = level;
}

export function showDebugLog(show: boolean): void {
  if (show) {
    _logLevel = hilog.LogLevel.DEBUG;
  } else if (_logLevel == hilog.LogLevel.DEBUG) {
    _logLevel = hilog.LogLevel.INFO;
  }
}

export function isDebugLog(): boolean {
  return _logLevel == hilog.LogLevel.DEBUG;
}

const _disabledLogNameList: string[] = [];

export function disableLogName(name: string): void {
  if (!_disabledLogNameList.includes(name)) {
    _disabledLogNameList.push(name);
  }
}

export function enableLogName(name: string): void {
  const index = _disabledLogNameList.indexOf(name);
  if (index >= 0) {
    _disabledLogNameList.splice(index, 1);
  }
}

function canLog(name: string, level: hilog.LogLevel): boolean {
  return level >= _logLevel && !_disabledLogNameList.includes(name);
}

export interface ILogger {
  trace(...args: unknown[]): void;

  debug(...args: unknown[]): void;

  info(...args: unknown[]): void;

  warn(...args: unknown[]): void;

  error(...args: unknown[]): void;

  fatal(...args: unknown[]): void;
}

export class Logger implements ILogger {
  private modules: string[] = [];
  maxLength: number = 2000
  name:string
  modulesInfo?:string
  constructor(name: string) {
    this.modules.push(name);
    this.name = name;
  }

  registerModules(modules:string[]) {
    this.modulesInfo = undefined;
    this.modules = modules;
  }

  getModulesInfo() {
    if(!this.modulesInfo) {
      this.modulesInfo = `[${this.modules.join()}]`
    }
    return this.modulesInfo;
  }


  setLineLimit(max: number): void {
    this.maxLength = max;
  }

  trace(...args: unknown[]): void {
    if (canLog(this.name, hilog.LogLevel.DEBUG)) {
      const s = toString(args);
      hilog.debug(2, this.getModulesInfo(), s);
      if (_handler) {
        _handler(hilog.LogLevel.DEBUG, new Date, `${this.getModulesInfo()} ${s}`)
      }
    }
  }

  debug(...args: unknown[]): void {
    if (canLog(this.name, hilog.LogLevel.DEBUG)) {
      const s = toString(args, this.maxLength);
      hilog.debug(1, this.getModulesInfo(), s);
      if (_handler) {
        _handler(hilog.LogLevel.DEBUG, new Date, `${this.getModulesInfo()} ${s}`);
      }
    }
  }

  info(...args: unknown[]): void {
    if (canLog(this.name, hilog.LogLevel.INFO)) {
      const s = toString(args, this.maxLength);
      hilog.info(1, this.getModulesInfo(), s);
      if (_handler) {
        _handler(hilog.LogLevel.INFO, new Date, `${this.getModulesInfo()} ${s}`);
      }
    }
  }

  warn(...args: unknown[]): void {
    if (canLog(this.name, hilog.LogLevel.WARN)) {
      const s = toString(args, this.maxLength);
      hilog.warn(1, this.getModulesInfo(), s);
      if (_handler) {
        _handler(hilog.LogLevel.WARN, new Date, `${this.getModulesInfo()} ${s}`);
      }
    }
  }

  error(...args: unknown[]): void {
    if (canLog(this.name, hilog.LogLevel.ERROR)) {
      const s = toString(args);
      hilog.error(1, this.getModulesInfo(), s);
      if (_handler) {
        _handler(hilog.LogLevel.ERROR, new Date, `${this.getModulesInfo()} ${s}`);
      }
    }
  }

  fatal(...args: unknown[]): void {
    if (canLog(this.name, hilog.LogLevel.FATAL)) {
      const s = toString(args);
      hilog.fatal(1, this.getModulesInfo(), s);
      if (_handler) {
        _handler(hilog.LogLevel.FATAL, new Date, `${this.getModulesInfo()} ${s}`);
      }
    }
  }

  log(...args: unknown[]): void {
    this.info(...args);
  }
}

export function getLogger(name: string): Logger {
  return new Logger(name);
}

export const logger = new Logger('__stu');

export function setLoggerHandler(handler: LogHandler) {
  _handler = handler;
}
